// 引入三个接口
// logout 是一个退出登录的接口
import { login, logout, getInfo } from '@/api/user'
// getToken 获取token
// setToken 设置token
// removeToken  删除token
import { getToken, setToken, removeToken } from '@/utils/auth'
// 引入路由器 resetRouter重置路由系统
// 为什么要重置？
//  如果一个用户退出登录，另一个新的用户去登录，路由系统，就需要恢复原始状态
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),  // token  getToken()从cookie中获取token
  name: '', //  用户名
  avatar: '', //  用户头像
  introduction: '', //用户介绍
  roles: [] // 当前用户所具备的角色
}

// mutations改变状态的唯一途径
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // 登录
  login({ commit }, userInfo) {
    const { username, password, code } = userInfo
    return new Promise((resolve, reject) => {
      login({ user_code: username.trim(), password: password, code: code }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  logout({ commit, state, dispatch }) {
    commit('SET_TOKEN', '')
    commit('SET_ROLES', [])
    removeToken()
    resetRouter()
    dispatch('tagsView/delAllViews', null, { root: true })
  },

  // 退出登录
  // logout({ commit, state, dispatch }) {
  //   return new Promise((resolve, reject) => {
  //     // 退出登录，不需要调用接口
  //     logout(state.token).then(() => {
  //       commit('SET_TOKEN', '')   //把token设置为空
  //       commit('SET_ROLES', [])   //把roles设置为空
  //       removeToken()   //把cookie中的token删除掉
  //       resetRouter()   //路由重置，把之前计算出来的路由规则，重置掉

  //       // reset visited views and cached views
  //       // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
  //       // 删除所有tagsView
  //       dispatch('tagsView/delAllViews', null, { root: true })

  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // 重置token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
